package org.jeecg.modules.thread;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.entity.Order;
import org.jeecg.modules.entity.Posi;
import org.jeecg.modules.service.IOrderService;
import org.jeecg.modules.service.IPosiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Random;

/**
 * @author Administrator
 */
@Slf4j
@Component
public class OrderThreadPoolMock {

    Random random = new Random();

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IPosiService posiService;


    @Transactional(rollbackFor = Exception.class)
    public synchronized void mock() {
        //随机用户
        int index = random.nextInt(Order.uidList.size()-1);
        Long uid = Order.uidList.get(index);
        //随机股票
        index = random.nextInt(Order.codeList.size()-1);
        Integer code = Order.codeList.get(index);
        //查询持仓数量
        LambdaQueryWrapper<Posi> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Posi::getUid, uid).eq(Posi::getCode, code);
        Posi posi = posiService.getOne(queryWrapper);
        if (posi != null) {
            //交易中的买入股票数据
            LambdaQueryWrapper<Order> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderLambdaQueryWrapper.eq(Order::getUid, uid).eq(Order::getCode, code).eq(Order::getStatus,0).eq(Order::getDirection,1);
            List<Order> list = orderService.list(orderLambdaQueryWrapper);
            long sum = list.stream().mapToLong(item -> item.getOcount()).sum();
            //最大的可卖数据
            long max = posi.getCount() - sum;
            posi.setCount(max);
        }
        //随机生成订单
        Order order = Order.generateRandomOrder(uid, code, posi == null ? 0L : posi.getCount().intValue());
        orderService.save(order);
        log.info("模拟数据：{}", order);

    }


    @PostConstruct
    public void init() {
        threadPoolTaskExecutor.execute(()->{
            while (true) {
                try {
                    mock();
                    Thread.sleep(100);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        threadPoolTaskExecutor.execute(()->{
            while (true) {
                try {
                    mock();
                    Thread.sleep(100);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

}
